package com.wing.sell.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wing.common.enums.ProductEnum;
import com.wing.common.enums.PurEnum;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.sell.dao.SelReturnGoodsRecordsDao;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.request.SelGoodsLogisticsDetailAddForm;
import com.wing.sell.model.request.SelReturnGoodRecordsUpdateForm;
import com.wing.sell.model.response.SelReturnGoodRecordsSearchVo;
import com.wing.sell.service.*;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 退货记录-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class SelReturnGoodsRecordsServiceImpl extends ServiceImpl<SelReturnGoodsRecordsDao, SelReturnGoodsRecords> implements SelReturnGoodsRecordsService {

    @Autowired
    private SelReturnGoodsRecordsDetailService selReturnGoodsRecordsDetailService;

    @Autowired
    private FinishedOrderService finishedOrderService;

    @Autowired
    private CustomersInfoService customersInfoService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SelGoodsLogisticsService selGoodsLogisticsService;

    @Autowired
    private SelGoodsLogisticsDetailService selGoodsLogisticsDetailService;

    /**
     * 查询退货记录
     *
     * @param pg
     * @param params
     * @return
     */
    @Override
    public Page<SelReturnGoodRecordsSearchVo> pageList4app(Page<SelReturnGoodRecordsSearchVo> pg, Map<String, Object> params) {
        List<SelReturnGoodRecordsSearchVo> list = baseMapper.list4app(pg, params);
        pg.setRecords(list);
        return pg;
    }


    /**
     * 添加退货记录
     *
     * @param selReturnGoodRecordsUpdateForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addReturnRecordsGoods(SelReturnGoodRecordsUpdateForm selReturnGoodRecordsUpdateForm) {
        //1. 添加退货信息
        SelReturnGoodsRecords selReturnGoodsRecords = new SelReturnGoodsRecords();
        BeanUtil.copyProperties(selReturnGoodRecordsUpdateForm, selReturnGoodsRecords, false);
        selReturnGoodsRecords.setCreateTime(LocalDateTime.now());
        selReturnGoodsRecords.setCreatorName(JwtUtils.getLoginUsername());
        selReturnGoodsRecords.setCreator(JwtUtils.getLoginUserId());
        //状态设置为待审核
        selReturnGoodsRecords.setStatus(PurEnum.barterGoodStatus.DSH.getCode());
        String code = UniqueIdGeneratorUtil.generateUniqueId("TH", "yyyyMMdd", 1000, 9999);
        selReturnGoodsRecords.setCode(code);

        boolean save = this.save(selReturnGoodsRecords);
        if (save) {
            //如果添加成功
            List<SelReturnGoodsRecordsDetail> goodsRecordsDetails = selReturnGoodRecordsUpdateForm.getSelReturnGoodsRecordsDetails();
            goodsRecordsDetails.forEach(info -> {
                info.setRecordId(selReturnGoodsRecords.getId());
                info.setCreateTime(LocalDateTime.now());
                info.setCreator(JwtUtils.getLoginUserId());
                info.setShipmentQty(info.getMainQuantity());
                info.setCreatorName(JwtUtils.getLoginUsername());
            });
            if (CollectionUtil.isNotEmpty(goodsRecordsDetails)) {
                boolean b = this.selReturnGoodsRecordsDetailService.saveBatch(goodsRecordsDetails);
                if (b) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
        return 0;
    }

    /**
     * 修改退货记录
     *
     * @param form
     * @return
     */
    @Override
    public int updateReturnRecordsGoods(SelReturnGoodRecordsUpdateForm form) {
        //1.修改记录
        SelReturnGoodsRecords byId = this.getById(form.getId());
        BeanUtil.copyProperties(form, byId, true);
        byId.setStatus(PurEnum.returnGoodStatus.DSH.getCode());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        boolean b = this.updateById(byId);
        if (b) {
            QueryWrapper<SelReturnGoodsRecordsDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("record_id", byId.getId());
            boolean remove = selReturnGoodsRecordsDetailService.remove(queryWrapper);
            if (remove) {
                List<SelReturnGoodsRecordsDetail> selReturnGoodsRecordsDetails = form.getSelReturnGoodsRecordsDetails();
                if (CollectionUtils.isNotEmpty(selReturnGoodsRecordsDetails)) {
                    selReturnGoodsRecordsDetails.forEach(info -> {
                        info.setRecordId(byId.getId());
                        info.setCreateTime(LocalDateTime.now());
                        info.setCreatorName(JwtUtils.getLoginUsername());
                        info.setShipmentQty(info.getMainQuantity());
                        info.setCreator(JwtUtils.getLoginUserId());
                    });
                    boolean saveBatch = selReturnGoodsRecordsDetailService.saveBatch(selReturnGoodsRecordsDetails);
                    if (saveBatch) {
                        return 1;
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 查询销售退货详情
     *
     * @param recordId
     * @return
     */
    @Override
    public SelReturnGoodRecordsUpdateForm getByDetailId(String recordId) {
        SelReturnGoodRecordsUpdateForm form = new SelReturnGoodRecordsUpdateForm();
        //1.查询记录信息
        SelReturnGoodsRecords byId = this.getById(recordId);
        BeanUtil.copyProperties(byId, form, true);
        //2. 查询明细信息
        QueryWrapper<SelReturnGoodsRecordsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_id", recordId);
        List<SelReturnGoodsRecordsDetail> list = this.selReturnGoodsRecordsDetailService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            form.setSelReturnGoodsRecordsDetails(list);
        }

        //查询供应商
        List<CustomersInfo> customersInfos = customersInfoService.list();
        //设置订单编号
        if (StrUtil.isNotEmpty(byId.getTypeCode())) {
            //1.成品出库
            if (byId.getTypeCode().equals(ProductEnum.outTypeEmum.CPC.getCode())) {
                FinishedOrder orderServiceById = finishedOrderService.getById(byId.getOrderId());
                if (orderServiceById != null) {
                    form.setOrderCode(orderServiceById.getSelCode());
                }
            }
            //2.生产出库
            else if (byId.getTypeCode().equals(ProductEnum.outTypeEmum.SCDC.getCode())) {
                Order info = orderService.getById(byId.getOrderId());
                if (byId != null) {
                    form.setOrderCode(info.getCode());
                }
            }

            for (CustomersInfo customersInfo : customersInfos) {
                if (null != byId.getSupplierId() && customersInfo.getId().equals(byId.getSupplierId())) {
                    form.setSupplierName(customersInfo.getCustomerName());
                }
            }

            //查询 退货收货信息
            QueryWrapper<SelGoodsLogistics> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("record_id", byId.getId());
            detailQueryWrapper.eq("module_type", PurEnum.moduleTypeBylogistics.XSTH.getCode());
            detailQueryWrapper.eq("good_type", PurEnum.goodSellType.TH.getCode());
            detailQueryWrapper.eq("is_deleted", false);
            List<SelGoodsLogistics> infos = this.selGoodsLogisticsService.list(detailQueryWrapper);
            //查询 退换详情
            for (SelGoodsLogistics selGoodsLogistics : infos) {
                List<SelGoodsLogisticsDetail> details = this.selGoodsLogisticsDetailService.getListBy(selGoodsLogistics.getId());
                selGoodsLogistics.setSelGoodsLogisticsDetails(details);
            }
            form.setGetSelGoodsLogisticsDetails(infos);
        }
        return form;
    }

    /**
     * 删除退货记录
     *
     * @param recordId
     * @return
     */
    @Override
    public boolean deleteBy(String recordId) {
        boolean b = this.removeById(recordId);
        if (b) {
            QueryWrapper<SelReturnGoodsRecordsDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("record_id", recordId);
            boolean remove = this.selReturnGoodsRecordsDetailService.remove(detailQueryWrapper);
            if (remove) {
                return true;
            }
        }
        return false;
    }

    /**
     * 退货收货信息
     *
     * @param selBarterGoodRecordsUpdateForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addLogisticsInfo(SelGoodsLogisticsDetailAddForm selBarterGoodRecordsUpdateForm) {
        //添加发货记录
        SelGoodsLogistics selGoodsLogistics = new SelGoodsLogistics();
        BeanUtil.copyProperties(selBarterGoodRecordsUpdateForm, selGoodsLogistics, false);
        selGoodsLogistics.setCreateTime(LocalDateTime.now());
        selGoodsLogistics.setModifier(JwtUtils.getLoginUserId());
        selGoodsLogistics.setCreator(JwtUtils.getLoginUserId());
        //code
        String code = UniqueIdGeneratorUtil.generateUniqueId("THWL", "yyyyMMdd", 1000, 9999);
        selGoodsLogistics.setCode(code);
        selGoodsLogistics.setCreatorName(JwtUtils.getLoginUsername());
        boolean save = selGoodsLogisticsService.save(selGoodsLogistics);
        if (save) {
            //拿到详情
            List<SelGoodsLogisticsDetail> formDetails = selBarterGoodRecordsUpdateForm.getDetails();
            for (SelGoodsLogisticsDetail formDetail : formDetails) {
                formDetail.setLogisticsId(selGoodsLogistics.getId());
                formDetail.setCreateTime(LocalDateTime.now());
                formDetail.setModifier(JwtUtils.getLoginUserId());
                formDetail.setCreatorName(JwtUtils.getLoginUsername());
                formDetail.setCreator(JwtUtils.getLoginUserId());
            }
            //插入发货详情
            boolean saved = selGoodsLogisticsDetailService.saveBatch(formDetails);
            if (saved) {
                //1. 修改record的信息
                Long recordId = selBarterGoodRecordsUpdateForm.getRecordId();
                SelReturnGoodsRecords byId = this.getById(recordId);
                //收货
                if (selBarterGoodRecordsUpdateForm.getGoodType().equals(PurEnum.goodSellType.TH.getCode())){
                    //查询当前是否全部签收完毕
                    QueryWrapper<SelReturnGoodsRecordsDetail> detailQueryWrapper = new QueryWrapper<>();
                    detailQueryWrapper.eq("record_id", recordId);
                    List<SelReturnGoodsRecordsDetail> list = this.selReturnGoodsRecordsDetailService.list(detailQueryWrapper);
                    AtomicReference<Boolean> isOk = new AtomicReference<>(true);
                    if (CollectionUtils.isNotEmpty(list)) {
                        list.forEach(info->{
                            //获取
                            BigDecimal result = this.baseMapper.getGetQuantityForLogistics(info.getId(),PurEnum.moduleTypeBylogistics.XSTH.getCode());
                            if (result.compareTo(info.getMainQuantity())<0){
                                isOk.set(false);
                            }
                        });
                    }
                    if (isOk.get()) {
                        byId.setStatus(PurEnum.barterGoodStatus.YQS.getCode());
                    }
                }
                //设置状态为已收货
                byId.setCreateTime(LocalDateTime.now());
                byId.setModifier(JwtUtils.getLoginUserId());
                byId.setModifierName(JwtUtils.getLoginUsername());
                byId.setFileName(selBarterGoodRecordsUpdateForm.getFileName());
                byId.setFileUrl(selBarterGoodRecordsUpdateForm.getFileUrl());
                byId.setMethod(selBarterGoodRecordsUpdateForm.getReturnType());
                boolean b = this.updateById(byId);
                if (b){
                    return 1;
                }
            }


        }
        return 0;
    }

}
